let map = null;
let loca = null;
let allCustomPolygon = []
let allPolygon = []
let regionChildInfo = []
let allText = []

var hotAdministrativeItem = document.getElementById("administrative_container"); // 热门事项列表滚动区域元素
var hotAdministrativeItemCon = document.getElementById("administrative_hotCon"); // 热门事项列表元素
var hotItemSpeed = 50; // 热门事项滚动速度
var hotItemTimer = null;

// 添加多边形
function addPolygon(data, name, isSetFitView, parentName, device, zIndex, strokeStyle, fillColor) {
  var polygon = new AMap.Polygon({
    path: data,
    strokeColor: "#2b8cbe",
    strokeOpacity: 1,
    strokeWeight: 1,
    fillColor: zIndex === 20 ? fillColor : "lightskyblue",
    fillOpacity: zIndex === 20 ? 1 : 0.3,
    strokeStyle: strokeStyle,
    strokeDasharray: [5, 5],
    zIndex: zIndex
  });
  map.add(polygon);
  // polygon.setMap(map);
  allCustomPolygon.push(polygon)
  
  // 获取路径的中心点（用于显示地区名称）
  let centerPoint = polygon.getBounds().getCenter();

  // 创建文本标注
  // let text = new AMap.Text({
  //     text: device !== undefined ? `${name} ${device}台` : ' ', // 要显示的地区名称
  //     position: centerPoint, // 设置文本标注的位置为路径的中心点
  //     map: map, // 指定要显示的地图
  //     style: {
  //       backgroundColor: 'transparent', // 背景透明
  //       border: 'none', // 无边框
  //       fontSize: '18px', // 字体大小
  //       color: '#fff', // 文字颜色
  //       textAlign: 'center'
  //     },
  //     zooms: [map.getZoom(), 20]
  // });
  // 将文本标注添加到地图
  // text.setMap(map);

  if (isSetFitView) {
    setFitViewToMap()
  } else {
    const obj = {
      name: name,
      parentName: parentName,
      polygon: polygon,
      // text: text,
    }
    allPolygon.push(obj)
  }

  // 添加点击事件
  // polygon.on('click', function(e) {
  //   // 在这里处理多边形的点击事件
  //   const region = regionChildInfo.find(item => item.name === name);
  //   if (region && region.code) {
  //     const parentPolyline = allPolygon.find(item => item.parentName === name || item.name === name);
  //     if (parentPolyline) {
  //       const toRemovePolygon = [];
  //       allPolygon.forEach((item, index) => {
  //         if (item.parentName === name || item.name === name) {
  //           item.polygon.setMap(null);
  //           item.text.setMap(null);
  //           toRemovePolygon.unshift(index); // 反向插入以便正确删除
  //         }
  //       });
  //       toRemovePolygon.forEach(index => allPolygon.splice(index, 1));
  //     } else {
  //       // 调用drawPolygon获取新的区域数据
  //       drawPolygon(region.regionChildInfo, name, false, 20, 'solid');
  //     }
  //   }
  // });
}

function setFitViewToMap() {
  if (allCustomPolygon.length > 0) {
    map.setFitView(allCustomPolygon, false, [140, 100, 100, 100])
  }
}

// 绘制多边形
function drawPolygon(data, parentName, isSetFitView, zIndex, strokeStyle) {
  let mapData = data;
  regionChildInfo.push(...mapData);
  mapData.forEach((item, index) => {
    if (item.coordinates && item.coordinates.length > 0) {
      const coordinates = JSON.parse(item.coordinates)
      addPolygon(coordinates, item.name, isSetFitView, parentName, item.device, zIndex, strokeStyle, item.fillColor)
      // 递归渲染子级多边形（如果有）
      if (item.regionChildInfo && item.regionChildInfo.length > 0) {
        drawPolygon(item.regionChildInfo, item.name, false, 20, 'solid');
      }
    }
  })
}

let hallList = []
let lngLatArray = []
let markList = []
let lastMarkList = []
let textList = []
let lastTextList = []
let newData = []

// 绘制点标记
function drawMarker() {
  markList = []
  textList = []
  lastMarkList = []
  lastTextList = []
  hallList = hallListObj.data.filter(item => item.hallPosition && item.hallPosition.length > 0)
  setMarkerData(hallList)
}

const zzjList = [ 
  {
    icon: "./images/index/green.png",
    positionCategory: "6"
  },
   {   
    icon: "./images/index/orange.png",
    positionCategory: "7"
  },
   {
    icon: "./images/index/blue.png",
    positionCategory: "5"
  },
   {
    icon: "./images/index/red.png",
    positionCategory: "4"
  },
];

function setMarkerData(data) {
  data.forEach((item) => {
    let lngLat = item.hallPosition.split(',').map(Number);
    let content = `
      <p style="margin: 6px 0; color: #333">名称 : ${item.hallName}</p>
      <p style="margin: 6px 0; color: #333">电话 : ${item.contactNumber ? item.contactNumber : '无'} </p>
      <p style="margin: 6px 0; color: #333">位置 : ${item.positionInfo ? item.positionInfo : '无'} </p>`;
    let img = zzjList.find(zzj => zzj.positionCategory === item.positionCategory)?.icon
    checkDimensionImg(lngLat, img, content)
  })
}

async function checkDimensionImg(lngLat, img, content) {
  const icon = new AMap.Icon({
    image: img, // 图标图片路径
    size: new AMap.Size(20, 20), // 图标大小，这里设置为 32x32 像素
    imageSize: new AMap.Size(20, 20) // 保持图片原始大小，若不设置，图片会按 size 属性缩放
  });

  let marker = new AMap.Marker({
    position: lngLat,
    icon: icon,
    offset: new AMap.Pixel(-10, -20),
    zIndex: 10,
  });
  let infoWindow = new AMap.InfoWindow({
    content: content,
    offset: new AMap.Pixel(0, -30),
    autoMove: true,
  });   
  marker.on("click", function () {
    infoWindow.open(map, marker.getPosition());
  }); 
  map.add([marker, infoWindow]);
}

const chartIconList = [
  "./images/index/paiming_1.png",
  "./images/index/paiming_2.png",
  "./images/index/paiming_3.png",
  "./images/index/paiming_4.png",
  "./images/index/paiming_5.png",
  "./images/index/paiming_6.png",
  "./images/index/paiming_7.png",
  "./images/index/paiming_8.png",
  "./images/index/paiming_9.png",
  "./images/index/paiming_10.png",
  "./images/index/paiming_11.png",
  "./images/index/paiming_12.png",
  "./images/index/paiming_12.png",
  "./images/index/paiming_12.png",
  "./images/index/paiming_12.png",
  "./images/index/paiming_12.png",
  "./images/index/paiming_12.png",
  "./images/index/paiming_12.png",
];

// 渲染各层级终端数量
function renderTreminalCount() {
  var chartDom = document.getElementById('cityTerminalCount');
  var myChart = echarts.init(chartDom);
  var option = {
    legend: {
      show: false,
    },
    grid: {
      left: "80",
      right: "16%",
      top: "0%",
      bottom: "0%",
    },
    xAxis: [
      {
        splitLine: {
          show: false,
        },
        type: "value",
        show: false,
      },
    ],
    yAxis: [
      {
        splitLine: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        type: "category",
        axisTick: {
          show: false,
        },
        data: cityTerminalAmount.map(item => item.name),
        inverse: true,
        axisLabel: {
          color: "#fff",
          fontSize: 12,
          margin: 10,
          formatter: function (value, index) {
            return `{img${index}|}{value|${value}}`;
          },
          rich: {
            value: {
              width: 45,
            },
            img0: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[0],
              },
            },
            img1: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[1],
              },
            },
            img2: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[2],
              },
            },
            img3: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[3],
              },
            },
            img4: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[4],
              },
            },
            img5: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[5],
              },
            },
            img6: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[6],
              },
            },
            img7: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[7],
              },
            },
            img8: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[8],
              },
            },
            img9: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[9],
              },
            },
            img10: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[10],
              },
            },
            img11: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[11],
              },
            },
            img12: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[12],
              },
            },
            img13: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[13],
              },
            },
            img14: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[14],
              },
            },
            img15: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[15],
              },
            },
          },
        }
      },
      {
        type: "category",
        inverse: true,
        axisTick: "none",
        axisLine: "none",
        show: true,
        axisLabel: {
          textStyle: {
            color: "#fff",
            fontWeight: 700,
          },
          formatter: function (value) {
            return value;
          },
        },
        data: cityTerminalAmount.map(item => item.value),
      },
    ],
    series: [
      {
        name: "终端数量",
        type: "bar",
        barWidth: 6,
        MaxSize: 0,
        showBackground: true,
        backgroundStyle: {
          color: "rgba(255, 255, 255, 0.1)",
        },
        label: {
          show: false,
        },
        data: cityTerminalAmount.map(item => {
          return {
            name: item.name,
            value: item.value,
            itemStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 1,
                y2: 1,
                colorStops: [
                  {
                    offset: 1,
                    color: "rgb(174, 44, 234)",
                  },
                  {
                    offset: 0,
                    color: "rgba(111, 84, 128, 0)",
                  },
                ],
              }
            }
          }
        })
      }
    ]
  };
  myChart.setOption(option)
}

// 渲染各模块使用次数
function renderModuleCount() {
  var chartDom = document.getElementById('moduleUsedCount');
  var myChart = echarts.init(chartDom);
  var option = {
    legend: {
      show: false,
    },
    grid: {
      left: "100",
      right: "16%",
      top: "0%",
      bottom: "0%",
    },
    xAxis: [
      {
        splitLine: {
          show: false,
        },
        type: "value",
        show: false,
      },
    ],
    yAxis: [
      {
        splitLine: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        type: "category",
        axisTick: {
          show: false,
        },
        inverse: true,
        data: moduleUsedCount.map((item) => item.name),
        axisLabel: {
          color: "#fff",
          fontSize: 12,
          margin: 10,
          formatter: function (value, index) {
            return `{img${index}|}{value|${value}}`;
          },
          rich: {
            value: {
              width: 65,
            },
            img0: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[0],
              },
            },
            img1: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[1],
              },
            },
            img2: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[2],
              },
            },
            img3: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[3],
              },
            },
            img4: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[4],
              },
            },
            img5: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[5],
              },
            },
            img6: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[6],
              },
            },
            img7: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[7],
              },
            },
            img8: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[8],
              },
            },
            img9: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[9],
              },
            },
            img10: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[10],
              },
            },
            img11: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[11],
              },
            },
            img12: {
              width: 24,
              height: 16,
              backgroundColor: {
                image: chartIconList[12],
              },
            },
          },
        },
      },
      {
        type: "category",
        inverse: true,
        axisTick: "none",
        axisLine: "none",
        show: true,
        axisLabel: {
          textStyle: {
            color: "#fff",
            fontWeight: 700,
          },
          formatter: function (value) {
            return value;
          },
        },
        data: moduleUsedCount.map((item) => item.value),
      },
    ],
    series: [
      {
        name: "事项发布数",
        type: "bar",
        barWidth: 6, // 柱子宽度
        MaxSize: 0,
        showBackground: true,
        backgroundStyle: {
          color: "rgba(255, 255, 255, 0.1)",
        },
        label: {
          show: false,
        },
        data: moduleUsedCount.map((item, index) => {
          return {
            name: item.name,
            value: item.value,
            itemStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 1,
                y2: 1,
                colorStops: [
                  {
                    offset: 1,
                    color: "rgb(97, 231, 137)",
                  },
                  {
                    offset: 0,
                    color: "rgba(61, 82, 83, 0)",
                  },
                ],
              },
            },
          };
        }),
      },
    ],
  };
  myChart.setOption(option);
}

// 渲染政务事项
function renderAdministrative(type) {
  var data = type === 'zw' ? administrativeData : proveData
  var hotContainer = document.getElementById("administrative_hotCon")
  var str = "";
  // 清空旧内容
  hotContainer.innerHTML = "";

  data.forEach((item, index) => {
    str += "<tr>";
    if (index < 9) {
      str +=
        '<td style="width: 20%;font-style: italic;">0' +
        (index + 1) +
        "</td>";
    } else {
      str +=
        '<td style="width: 20%;font-style: italic;">' +
        (index + 1) +
        "</td>";
    }
    str +=
      '<td style="text-align:left;width: 60%;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;padding-right: 10rem;">' +
      item.name +
      "</td>" +
      '<td style="width: 20%;text-align:left">' +
      item.count +
      "</td>" +
      "</tr>";
  });
  hotContainer.innerHTML = str;
  hotItemListRoll()
}

function hotItemListRoll() {
  clearInterval(hotItemTimer); // 清除旧定时器
  hotAdministrativeItemCon.innerHTML += hotAdministrativeItemCon.innerHTML; // 列表数据复制实现循环滚动
  hotAdministrativeItem.scrollTop = 0; // 重置滚动位置
  hotItemTimer = setInterval(hotItemListRollStop, hotItemSpeed); // 创建新定时器
}

function hotItemListRollStop() {
  if (hotAdministrativeItem.scrollTop >= hotAdministrativeItemCon.scrollHeight / 2) {
    hotAdministrativeItem.scrollTop = 0; // 回到顶部
  } else {
    hotAdministrativeItem.scrollTop++; // 逐像素滚动
  }
}

// 鼠标移入
hotAdministrativeItem.onmouseover = function () {
  clearInterval(hotItemTimer);
};
// 鼠标移除
hotAdministrativeItem.onmouseout = function () {
  hotItemTimer = setInterval(hotItemListRollStop, hotItemSpeed);
};

// 渲染操作行为
function renderActionCount() {
  var chartDom = document.getElementById('actionCount');
  var myChart = echarts.init(chartDom);

  var option = {
    legend: {
      show: false,
    },
    grid: {
      bottom: '0%',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {d}%',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      padding: 10,
      textStyle: {
        color: '#333'
      }
    },
    color: ["#66E1DF", "#ce2772", "#0092FF", "#6F5EF9", "#F6BD16", "#D37295", "#5AD8A6", "#96BFFF"],
    series: [
      {
        name: "操作行为",
        type: "pie",
        radius: ["90%", "75%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 0,
          borderColor: "#1a202a",
          borderWidth: 5,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: actionData,
      },
    ],
  };
  myChart.setOption(option);
}


$(function () {
  // 创建地图实例
  map = new AMap.Map("map", {
    center: [112.978606, 37.667027],
    zoom: 7,
    mapStyle: "amap://styles/grey",
    viewMode: "3D",
    features: ["bg", "road", "building", "point"],
  })

  loca = new Loca.Container({
    map: map
  });

  // 绘制多边形
  drawPolygon(shanxi, null, true, 10, 'dashed');
  // 绘制点标记
  drawMarker();

  // 渲染各地市终端数量柱状图
  renderTreminalCount();

  // 渲染各模块使用次数
  renderModuleCount();

  // 渲染政务事项
  renderAdministrative('zw');

  // 渲染操作行为
  renderActionCount();

  $(".perTownCount>div").click(function () {
    $(this).parents(".perTownCount").find("div").removeClass("active");
    $(this).addClass("active");
    var type = $(this).attr("data-type");
    renderAdministrative(type);
  });

  $("#head").hide();

  $("#head").load("./header.html", function (response, status, xhr) {
    // 缓存选择器结果
    const $bottomMenu = $(".bottomMenu");
    const $title = $(".header .fontyoushe.font36.mt10");
    const $englishText = $(".fontyoushe:contains('A map of every village in Wuxiang')");
    // 移除底部菜单
    $bottomMenu.remove();
    // 修改标题文字
    $title.text("长河自助便民终端运行一张图");
    // 隐藏指定元素
    $englishText.hide();

    // 显示 #head 元素
    $("#head").show();
  });
})